<template>
    <view class="content">
        <view
            id="DzMap"
            :prop="sender"
            :change:prop="renderMaps.handleAction"
        ></view>
        <view class="skjs-legend" v-show="showPop">
            <view class="skjs-col">
                <view class="max-value">
                    最大降水:{{
                        `${maxObj.qxaa01A020 || ' -- '}(${maxObj.qxaa01A100 || 0}mm)`
                    }}
                </view>
                <view class="legend-box">
                    <view class="legend-list">
                        <view
                            class="legend-item"
                            v-for="(item, index) in legendList"
                            :key="index"
                        >
                            <view class="item-num">{{ item.num }}站</view>
                            <view
                                class="item-color"
                                :style="{ background: item.color }"
                            ></view>
                            <view class="item-value">
                                {{ item.value }}
                            </view>
                        </view>
                    </view>
                    <view class="legend-unit">毫米</view>
                </view>
            </view>
        </view>
    </view>
</template>
<!-- 逻辑层 -->
<script>
import { getLoginMsg } from '@/utils/util'
export default {
    props: {
        dataList: {
            type: Array,
            default: () => [],
        },
        maxObj: {
            type: Object,
            default: () => ({}),
        },
    },
    data() {
        return {
            sender: {
                handle: '', //调用视图层方法的名字
                callback: '', //回调函数的名字
                options: null, //传递给视图层的数据
                rendCallback: '', //视图层的回调函数的名字（可选）暂时无用
                AdminCode: getLoginMsg()?.AdminCode,
            },
            legendList: [
                { color: '#95DC73', value: '0.1', num: '100' },
                { color: '#2FB522', value: '10', num: '20' },
                { color: '#35A1E0', value: '25', num: '0' },
                { color: '#0101E9', value: '50', num: '0' },
                { color: '#E600E6', value: '100', num: '0' },
                { color: '#8A0D37', value: '200', num: '0' },
            ],
            showPop: false,
        }
    },
    created() {},
    methods: {
        /**
         * 逻辑层传递数据到视图层 类似父传子
         *
         * @param handle 触发视图层的方法名称
         * @param callback 视图层的方法名称（可选）暂时无用
         * @param options 消息发送的配置选项
         * @param rendCallback 逻辑层的回调函数（可选）app无用
         */
        sendMsg(handle, callback, options, rendCallback) {
            this.sender = {
                handle,
                callback,
                options,
                rendCallback,
            }
        },
        /**
         * 视图层触发逻辑层方法 类似子传父
         * @param event callback 逻辑层的方法名称
         * @param event param 传递给逻辑层的数据
         */
        handleItemClick(event) {
            const handle = this[event.callback]
            handle && handle(event.param)
        },
        handleInit() {
            uni.showToast({
                title: '加载中',
                icon: 'loading',
                duration: 2000,
            })
            this.sendMsg('getListLuoJi', '', JSON.stringify(this.dataList))
            this.getJszdLevelList(this.dataList)
            this.showPop = true
        },
        getJszdColor(value) {
            let colorBar = [0.1, 10, 25, 50, 100, 200]
            switch (true) {
                case value > colorBar[0] && value <= colorBar[1]:
                    return '#95DC73'
                case value > colorBar[1] && value <= colorBar[2]:
                    return '#2FB522'
                case value > colorBar[2] && value <= colorBar[3]:
                    return '#35A1E0'
                case value > colorBar[3] && value <= colorBar[4]:
                    return '#0101E9'
                case value > colorBar[4] && value <= colorBar[5]:
                    return '#E600E6'
                case value > colorBar[5]:
                    return '#8A0D37'
                default:
                    return ''
            }
        },
        getJszdLevelList(list, option) {
            let levelList = {
                '#95DC73': [],
                '#2FB522': [],
                '#35A1E0': [],
                '#0101E9': [],
                '#E600E6': [],
                '#8A0D37': [],
            }
            list.forEach((item) => {
                let point = {
                    value: item.qxaa01A100,
                }
                let keyColor = this.getJszdColor(point.value)
                point.color = keyColor
                if (keyColor) {
                    levelList[keyColor].push(point)
                }
            })
            this.legendList.forEach((item) => {
                item.num = levelList[item.color].length
            })
        },
    },
}
</script>
<!-- 视图层 -->
<!-- <script> -->
<script module="renderMaps" lang="renderjs">
import DzMap from "@/map/index"
// import { anhuaBoundaryMapJson } from "@/map/mapJson/anhuaxiangzhen"
import Polygon from "ol/geom/Polygon"
import Feature from "ol/Feature"
import { Fill, Style } from "ol/style"
import kriging from "@/map/kriging.js"
import ImageLayer from "ol/layer/Image"
import ImageCanvas from "ol/source/ImageCanvas"
import { getCityCode } from '@/map/json/district'
let map = null
export default {
    data() {
        return {
          AdminCode:'430524'
        }
    },
    mounted() {
        this.initMap()
    },
    methods: {
        //监听逻辑层传递过来的数据
        handleAction(newValue, oldValue, ownerInstance, instance) {
            console.log("逻辑层传递过来的数据", newValue)
            if(newValue.AdminCode) this.AdminCode = newValue.AdminCode
            const handle = this[newValue.handle]
            let options = newValue.options
            // this.callback = newValue.callback
            if (!options) {
                options = undefined
            }
            if (!handle) {
                console.info("参数为标记需要执行的方法")
                return
            }
            handle(options)
        },
        initMap() {
            map = new DzMap("DzMap")
            let JSONData = this.getXzqhGeom();
            let features = map.format.converGeoJsonToFeature(JSONData)
            let geom = features[0].getGeometry()
            const leyers = map.layer.initLayer(geom)
            leyers.layer.forEach((el) => {
                const name = el.get("layerName")
                name === "矢量图层组" && el.setVisible(true)
                name === "影像图层组" && el.setVisible(false)
            })
            // 更换层级
            let extent = geom.getExtent()
            map.map.getView().fit(extent, {
                duration: 0, //过渡时间
                padding: [20, 20, 130, 20],
            })
            setTimeout(() => {
                this.$ownerInstance.callMethod('handleItemClick',{
                    callback:'handleInit'
                })
            }, 500);
        },
        // 获取行政区划
        getXzqhGeom() {
            let JsonData1 = getCityCode(this.AdminCode).data
            // let JsonData = anhuaBoundaryMapJson()
            return JsonData1
        },
        getListLuoJi(newValue) {
            if (newValue === "" || newValue === undefined || newValue === null)
                return
            const tempArr = JSON.parse(newValue)
            const params = {
                mapCenter: [116, 34],
                maxValue: 100,
                krigingModel: "exponential", // 'exponential':指数  'gaussian':高斯,'spherical':球体
                krigingSigma2: 0,
                krigingAlpha: 100,
                canvasAlpha: 0.5, //canvas图层透明度
            }
            const values = tempArr.map((item) => item.qxaa01A100 + '')
            const lngs = tempArr.map((item) => Number(item.qxaa01A070))
            const lats = tempArr.map((item) => Number(item.qxaa01A080))
            if (values.length > 2) {
                let variogram = kriging().train(
                    values,
                    lngs,
                    lats,
                    params.krigingModel,
                    params.krigingSigma2,
                    params.krigingAlpha,
                )
                let JSONData = this.getXzqhGeom().features[0]
                // const features = mapJSON.anhuaMapJson().features
                // features.forEach((feature) => {
                //     if (feature.properties.adcode == "430923") {
                //         JSONData = feature
                //     }
                // })
                const polygons = JSONData.geometry.coordinates[0]
                const grid = kriging().grid([polygons], variogram, 0.001)
                const canvasLayer = new ImageLayer({
                    source: new ImageCanvas({
                        canvasFunction: (
                            extent,
                            resolution,
                            pixelRatio,
                            size,
                            projection,
                        ) => {
                            let canvas = document.createElement("canvas")
                            canvas.width = size[0]
                            canvas.height = size[1]
                            canvas.style.display = "block"
                            //设置canvas透明度
                            let ctx = canvas.getContext("2d")
                            kriging().plot(
                                canvas,
                                grid,
                                [extent[0], extent[2]],
                                [extent[1], extent[3]],
                            )
                            return canvas
                        },
                        projection: "EPSG:4326",
                    }),
                })
                canvasLayer.setZIndex(14)
                map.map.addLayer(canvasLayer)
                canvasLayer.setOpacity(0.6)
            }
        },
    },
}
</script>
<style lang="scss" scoped>
.content {
    width: 100%;
    height: 100%;
    position: relative;

    #DzMap {
        width: 100%;
        height: 100%;
    }

    .skjs-legend {
        position: absolute;
        z-index: 99;
        bottom: 20rpx;
        font-size: 24rpx;
        padding: 0 20rpx;
        color: #ffffff;
        width: 100%;

        .skjs-col {
            background: #1a6aabd0;
            border-radius: 20rpx;
            padding: 10rpx 20rpx;
        }

        .legend-box {
            display: flex;
            align-items: center;
        }

        .legend-list {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .legend-unit {
            margin-left: 10rpx;
        }

        .max-value {
            margin-bottom: 10rpx;
        }

        .item-num {
            text-align: center;
        }

        .legend-item {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;
            width: 40rpx;

            .item-color {
                width: 100%;
                height: 20rpx;
            }
        }
    }
}
</style>
